import ApiCrm from "@/api/crm";
import ListView from "@/components/app/ListView";
import ByButton from "@/components/ui/ByButton";
import ByCheckbox from "@/components/ui/ByCheckbox";
import ByCol from "@/components/ui/ByCol";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import useFetch from "@/hooks/useFetch";
import Attendance from "@/packageProject/components/Attendance";
import { objectToQueryString } from "@/utils";

import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useMap, useSet } from "ahooks";
import pick from "lodash-es/pick";

/**
 * 生活费
 */
const LivingExpensesItem = ({
  source,
  checked,
  attendance,
  onClick,
}: {
  source;
  checked?: boolean;
  attendance?: any
  onClick: () => void;
}) => {
  return (
    <ByRow align="center" className="my-3" onClick={onClick}>
      <ByCheckbox checked={checked} onChange={onClick} />

      <ByCol span={"auto"} className="ml-2">
        <View
          className={`rounded-xl p-3 border-primary border-1 ${checked ? "bg-primary-light" : "bg-white border-white"
            }`}
        >
          <ByRow align="center" content="between">
            <ByCol span={"none"}>
              <ByText bold size="lg">
                {source?.workerName}
              </ByText>
              <View className="mt-2 text-second text-sm">
                {attendance?.workerType}
              </View>
            </ByCol>
            <ByCol span={"none"}>
              <Attendance source={attendance} />
            </ByCol>
          </ByRow>
        </View>
      </ByCol>
    </ByRow>
  );
};

// 生活费（目前只有泥工）
export default ({ intentCustomerId, source }: { intentCustomerId: number, source?: any }) => {

  const [map, { setAll }] = useMap()

  // 考勤记录
  const { data = [] } = useFetch<any>(ApiCrm.getWorkerAttendanceRecord, {
    defaultParams: [{ intentCustomerId }],
    // onAfter: (res: any) => res.workerAttendanceRecordList || [],
    onSuccess(res) {
      const _map = new Map()
      res.workerAttendanceRecordList.forEach(item => {
        _map.set(item.workerId, item)
      });

      setAll(_map)
    }
  });

  // 申请生活费的工人列表
  const [selected, { add, remove }] = useSet<any>();

  const toApply = () => {
    const query = {
      constructionProjectName: "生活费",
      workerType: "生活费",
      intentCustomerId,
      livingCost: 1,
    };

    Taro.navigateTo({
      url: `apply?` + objectToQueryString(query),
      success(res) {
        const map = new Map();

        [...selected].forEach((worker) => {
          const { templateDetailId, workerType } = source;
          let target = map.get(workerType);

          if (!target) {
            map.set(
              workerType,
              (target = {
                workerType,
                files: [],
                templateDetailId,
                workerPayItems: [],
              })
            );
          }
          target.workerPayItems.push(pick(worker, ["workerId", "workerName"]));
        });

        res.eventChannel.emit("acceptWorkers", [...map.values()]);
      },
    });
  };


  // 工人列表
  const workers = source?.workers || []

  return (
    <>
      <ListView isEmpty={workers.length === 0}>
        {workers?.map((item) => (
          <LivingExpensesItem
            source={item}
            key={item.workerDistributeId}
            checked={selected.has(item)}
            attendance={map.get(item.workerId)}
            onClick={() => (selected.has(item) ? remove(item) : add(item))}
          />
        ))}
      </ListView>

      {workers.length > 0 && (
        <View className="py-3  text-center">
          <ByButton inlineBlock disabled={selected.size == 0} onClick={toApply}>
            申请生活费
          </ByButton>
        </View>
      )}
    </>
  );
};
